package network;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class UdpEchoServer {
    //进行网络编程，第一步就需要先准备好socket实例，这是进行网络编程的大前提
    private DatagramSocket socket=null;

    public UdpEchoServer(int port) throws SocketException {
        socket=new DatagramSocket(port);
    }
    //启动服务器
    public void start() throws IOException {
        System.out.println("启动服务器！");
        //UDP不需要建立连接，直接接收从客户端来的数据即可
        while(true){
            //1、读取客户端发来的请求
            DatagramPacket requestPacket=new DatagramPacket(new byte[1024],1024);
            socket.receive(requestPacket);
            //把DatagramPacket解析成一个String
            String request=new String(requestPacket.getData(),0, requestPacket.getLength());
            //2、根据请求计算响应（由于是回显服务，2省略）
            String response=process(request);
            //3、把响应写回到客户端
            DatagramPacket responsePacket=new DatagramPacket(response.getBytes(),response.getBytes().length,requestPacket.getSocketAddress()) ;
            socket.send(responsePacket);
            System.out.printf("[%s:%d] req:%s, resp:%s\n", requestPacket.getAddress().toString(), requestPacket.getPort(),request,response);
        }
    }

    private String process(String request){
        return request;
    }

    public static void main(String[] args) throws IOException {
        UdpEchoServer server=new UdpEchoServer(9090);
        server.start();
    }
}
